package org.cleverframe.common.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.cleverframe.common.spring.SpringBeanNames;
import org.cleverframe.common.spring.SpringContextHolder;

/**
 * 
 * 
 * @author LiZhiWei
 * @version 2015年6月18日 下午9:23:22
 */
public class EhCacheUtils
{
	/** Ehcache的缓存管理器 */
	private static CacheManager CACHE_MANAGER = (CacheManager) SpringContextHolder.getBean(SpringBeanNames.CACHE_MANAGER);

	/**
	 * 得到Ehcahe的CacheManager
	 * */
	public static CacheManager getCacheManager()
	{
		return CACHE_MANAGER;
	}

    /**
    * 获得一个Cache，没有返回null<br>
    * @param cacheName Ehcache缓存名称，参考：EhCacheNames
    * @return Cache对象实例
    */
    public static Cache getCache(String cacheName)
    {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        return cache;
    }
	
	/**
	 * 创建一个新的Cache，若Cache已存在则直接返回<br>
	 * <b>注意：创建新的缓存要到EhCacheNames类中定义名称</b>
	 * @param cacheName Ehcache缓存名称，参考：EhCacheNames
	 * @return Cache对象实例
	 */
	public static Cache createCache(String cacheName)
	{
		Cache cache = CACHE_MANAGER.getCache(cacheName);
		if (cache == null)
		{
			CACHE_MANAGER.addCache(cacheName);
			cache = CACHE_MANAGER.getCache(cacheName);
			cache.getCacheConfiguration().setEternal(true);
		}
		return cache;
	}
	
	/**
	 * 从指定的缓存中删除对象<br>
	 * 
	 * @param cacheName 缓存名称，参考类：EhCacheNames
	 * @param key 缓存对象的主键
	 * */
    public static void remove(String cacheName, String key)
    {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        if (cache != null)
        {
            cache.remove(key);
        }
    }
	
	/**
	 * 把对象存入指定的缓存中<br>
	 * 
	 * @param cacheName 缓存名称，参考类：EhCacheNames
	 * @param key 缓存对象的主键
	 * @param value 缓存对象
	 * @return 操作成功返回true
	 * */
	public static boolean put(String cacheName, String key, Object value)
	{
		Element element = new Element(key, value);
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        if (cache == null)
        {
            return false;
        }
        cache.put(element);
        return true;
	}
	
	/**
	 * 从指定的缓存中取得对象<br>
	 * 
	 * @param cacheName 缓存名称，参考类：EhCacheNames
	 * @param key 缓存对象的主键
	 * @return 不存在返回null
	 * */
    public static Object get(String cacheName, String key)
    {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        if (cache == null)
        {
            return null;
        }
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }
}
